using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Text;
using System.Collections.Generic;
using Instedd.Labs.Geo.Library.Sms;
using Instedd.Labs.Geo.Library.Rss;
using Instedd.Labs.Geo.Library.Kml;
using Instedd.Labs.Forms.Library;

public partial class GetFeed : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        GenerateGeoRssFeed(GenerateGeoRssItems());
    }

    List<Item> GenerateGeoRssItems()
    {
        List<Item> items = new List<Item>();

        using (IDataReader reader = SurveyManager.GetInstance().GetSurveysAsDataReader())
        {
            while (reader.Read())
            {
                Item item = CreateItem(reader);
                if (item != null)
                {
                    items.Add(item);
                }
            }
        }

        return items;
    }

    Item CreateItem(IDataReader reader)
    {
        try
        {
            Survey survey = SurveyManager.GetInstance().CreateSurvey(reader);
            if (survey.Latitude == null || survey.Longitude == null)
            {
                return null;
            }

            string description = string.Format(WebSurveyManager.GetInstance().PushpinDescriptionTemplate,
                    survey.FirstName, survey.LastName,
                    new Uri(this.Request.Url, string.Format("GetSurvey.aspx?surveyid={0}", survey.ID)).AbsoluteUri, survey.ID,
                    survey.Comments,
                    survey.FollowUpComments,
                    survey.TotalExposed,
                    survey.TotalWell,
                    survey.TotalExposedNotIll,
                    survey.TotalExposedAndIll,
                    survey.TotalReceivedTreatment,
                    survey.TotalRecovered,
                    survey.TotalDeceased
                    );
            description = string.Concat(string.Format("<img src=\"{0}\" />", GetIconUrl(survey)), description);

            Item item = new Item(
                Guid.NewGuid(),
                survey.EnteredBy,
                string.Format("{0}", survey.ID),
                description.ToString(),
                survey.EnteredOn,
                new Uri(this.Request.Url, string.Format("GetSurvey.aspx?surveyid={0}", survey.ID)).AbsoluteUri,
                new LatLong((double)survey.Latitude, (double)survey.Longitude), 
                new List<Comment>()
                );

            return item;
        }
        catch
        {
            return null;
        }
    }

    // TODO: This should be refactored because it's being used by the KML generation as well.
    private string GetIconUrl(Survey survey)
    {
        string colorId = null;

        if (survey.TotalDeceased > 0)
        {
            colorId = "black";
        }
        else if (survey.TotalExposedAndIll > 0 && survey.ReceivedIvTreatment == 0)
        {
            colorId = "red";
        }
        else if (survey.TotalExposedAndIll > 0 && survey.ReceivedIvTreatment > 0)
        {
            colorId = "purple";
        }
        else if (survey.TotalExposedNotIll > 0 && survey.DoxyDistributed == 0 && survey.CiproDistributed == 0)
        {
            colorId = "blue";
        }
        else if (survey.TotalExposedNotIll > 0 && (survey.DoxyDistributed > 0 || survey.CiproDistributed > 0))
        {
            colorId = "pink";
        }
        else if (survey.TotalRecovered > 0)
        {
            colorId = "green";
        }
        else if (survey.TotalWell > 0)
        {
            colorId = "white";
        }

        return colorId != null ? new Uri(this.Request.Url, string.Format("img/icon_{0}.png", colorId)).AbsoluteUri : null;
    }

    void GenerateGeoRssFeed(List<Item> items)
    {
        Response.Clear();
        //Response.AppendHeader("Content-Disposition", "filename=feed.xml");
        Response.Buffer = false;
        Response.ContentType = "application/xml";
        Response.ContentEncoding = Encoding.UTF8;

        StringBuilder sb = new StringBuilder();

        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Encoding = Encoding.UTF8;
        XmlWriter writer = XmlWriter.Create(Response.OutputStream, settings);
        writer.Flush();

        RssFormat feed = new RssFormat();
        Channel channel = new Channel();
        channel.LastBuildDate = DateTime.Now;
        channel.Title = "InSTEDD Biosurveillance Forms";
        channel.PubDate = DateTime.Now;
        channel.Link = "http://bioforms.clariusconsulting.net";
        channel.Description = "Innovative Support for Emergencies Diseases and Disasters";
        channel.Items = items;

        feed.Channels.Add(channel);

        RssWriter rssWriter = new RssWriter();
        rssWriter.WriteRss(writer, feed);
        writer.Flush();
        Response.Write(sb.ToString());
        Response.End();
    }
}
